package com.mobile.ado.util;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.provider.ContactsContract;

import com.mobile.ado.contacts.Contact;
import com.mobile.ado.contacts.PhoneNumber;

public class ContactsUtil {

	public static ArrayList<Contact> getAllContacts(Context context,
			Cursor cursor) {
		ArrayList<Contact> contacts = new ArrayList<Contact>();

		while (cursor.moveToNext()) {

			String id = getContactId(cursor);
			String name = getContactName(cursor);
			Bitmap photo = getContactPhoto(cursor);

			ArrayList<PhoneNumber> contactList = getContactPhoneNumbers(
					context, id);

			Contact contact = new Contact(id, name, contactList, photo);

			contacts.add(contact);

		}

		return contacts;

	}

	private static ArrayList<PhoneNumber> getContactPhoneNumbers(
			Context context, String id) {
		Cursor phoneCusor = ContentProviderHelper.getAllPhoneNumbers(context,
				id);
		ArrayList<PhoneNumber> contactList = new ArrayList<PhoneNumber>();
		while (phoneCusor.moveToNext()) {
			int phoneNumberIndex = phoneCusor
					.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
			String phoneNumber = phoneCusor.getString(phoneNumberIndex);
			PhoneNumber phone = new PhoneNumber("", "", "", phoneNumber);
			contactList.add(phone);
		}
		return contactList;
	}

	private static Bitmap getContactPhoto(Cursor cursor) {
		int imageIndex = cursor
				.getColumnIndex(ContactsContract.Contacts.PHOTO_ID);

		try {
			byte[] imageBytes = cursor.getBlob(imageIndex);
			return BitmapFactory.decodeByteArray(imageBytes, 0,
					imageBytes.length);
		} catch (Exception e) {
			return null;
		}
	}

	private static String getContactName(Cursor cursor) {
		int nameIndex = cursor
				.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
		String name = cursor.getString(nameIndex);
		return name;
	}

	private static String getContactId(Cursor cursor) {
		int idIndex = cursor.getColumnIndex(ContactsContract.Contacts._ID);
		String id = cursor.getString(idIndex);
		return id;
	}

}
